<template>
  <base-modal
    :title="`${pageTitle}模型`"
    :width="560"
    cancelText="取消"
    :okText="pageTitle"
    v-on="$listeners"
    @ok="handleUpload"
    :confirmLoading="loading.isSaving"
  >
    <a-form-model ref="form" :rules="rules" :model="formInfo" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }" hideRequiredMark>
        <a-form-model-item label="选择模型">
                <a-upload name="file" :multiple="false" :fileList="fileList" :beforeUpload="beforeUpload" @change="handleUploadChanged">
      <a-button> <a-icon type="upload" />点击选择</a-button>
    </a-upload>
        </a-form-model-item>
      <a-form-model-item label="模型名称">
        <BaseInput
          placeholder="模型名称（若不输入，默认采用文件名）"
          v-model="formInfo.modelName"
          :maxLength="30"
        />
      </a-form-model-item>
      <a-form-model-item label="模型类别" prop="modelType">
          <a-select v-model="formInfo.modelType">
                <a-select-option
                  v-for="item in modelTypeList"
                  :key="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
          </a-select>
      </a-form-model-item>
      <a-form-model-item label="是否为主模型">
              <a-radio-group v-model="formInfo.isMain">
      <a-radio :value="true">
        是
      </a-radio>
      <a-radio :value="false">
        否
      </a-radio>
    </a-radio-group>
      </a-form-model-item>
    </a-form-model>
  </base-modal>
</template>

<script>
import { getTypeLabel } from '@/api/commons'
import { uploadModel, updateModel } from '@/api/bimIntegrate'
import { bindModelWithProject, updateBind } from '@/api/bimIntegrate/business.js'
import BaseModal from '@/components/BaseModal'

export default {
  components: {
    BaseModal,
  },
  props: {
    initData: {
      type: Object,
      default() {
        return {}
      },
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      fileName: '',
      modelTypeList: [],
      formInfo: {
        model: true, // 是否为模型
        modelName: '',
        modelType: '',
        isMain: true,
      },
      fileList: [],
      loading: {
        isSaving: false,
      },
      rules: {
        modelType: [{ required: true, message: '请选择', trigger: 'change' }],
      },
    }
  },
  computed: {
    pageTitle() {
      return this.isEdit ? '更新' : '上传'
    },
  },
  created() {
    this.initPage()
    this.getModelTypeList()
  },
  methods: {
    getModelTypeList() {
      getTypeLabel({ type: 4 }).then((res) => {
        this.modelTypeList = res.data || []
      })
    },
    initPage() {
      if (!this.isEdit) return
      const { modelName, main, model, modelCate } = this.initData
      this.formInfo = {
        ...this.formInfo,
        modelName,
        isMain: main,
        model,
        modelType: (modelCate && modelCate.id) || '',
      }
    },
    handleUploadChanged(info) {
      const { fileList } = info
      this.fileList = fileList
      if (fileList.length > 1) {
        this.fileList = [fileList.pop()]
      }
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file]
      return false
    },
    async bindModelWithProject(modelId) {
      const projectId = this.$store.getters['bimInfo/GET_PROJECTID']
      const { isMain, modelType, modelName, model } = this.formInfo
      const params = {
        id: this.initData.id || void 0,
        businessId: projectId,
        main: isMain, // 是否为主模型
        model, // 是否为模型（有模型或构件）
        modelCate: {
          // 模型类别
          id: modelType,
        },
        modelName,
        models: [
          // 模型信息
          {
            modelId: modelId,
            modelName: this.fileName,
          },
        ],
        type: 'PROJECT', // 绑定的业务类型
      }
      let bindResult = null
      if (this.isEdit) {
        bindResult = await updateBind(params)
      } else {
        bindResult = await bindModelWithProject(params)
      }
      const [bindErr, bindRes] = bindResult
      if (!bindErr) {
        this.fileList = []
        this.$message.success(`${this.pageTitle}成功`)
        this.$emit('confirm')
      }
    },
    handleUpload() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.loading.isSaving) return
          const { fileList } = this
          if (this.fileList.length === 0 && !this.isEdit) {
            this.$message.error('请选择模型文件')
            return
          }
          const { modelId } = this.initData
          const formData = new FormData()
          fileList.forEach((file) => {
            const fileName = this.formInfo.modelName !== '' ? this.formInfo.modelName : file.name.split('.')[0]
            this.fileName = fileName
            formData.append('name', fileName)
            formData.append('modelFile', file.originFileObj)
            if (this.isEdit) {
              formData.append('id', modelId)
            }
          })
          this.loading.isSaving = true
          if (this.fileList.length > 0) {
            // 区分是否需要更新模型版本(即是否需要上传模型文件)
            let result = null
            if (this.isEdit) {
              result = await updateModel({ modelId: modelId }, formData)
            } else {
              result = await uploadModel(formData)
            }
            const [err, res] = result
            if (!err) {
              // 上传模型成功之后，将模型和项目绑定
              this.bindModelWithProject(res.data._id)
            }
          } else {
            this.bindModelWithProject(modelId)
          }
          this.loading.isSaving = false
        }
      })
    },
  },
}
</script>

<style>
</style>